package cn.xydpeng.springframework.context.support;

import cn.xydpeng.springframework.beans.BeansException;
import cn.xydpeng.springframework.beans.factory.support.DefaultListableBeanFactory;
import cn.xydpeng.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import cn.xydpeng.springframework.context.ApplicationContext;
import cn.xydpeng.springframework.core.io.Resource;
import cn.xydpeng.springframework.lang.Nullable;

import java.io.IOException;
import java.io.Reader;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2022/10/17
 * @description:
 */
public abstract class AbstractXmlApplicationContext extends AbstractRefreshableApplicationContext {
    public AbstractXmlApplicationContext(){}

    public AbstractXmlApplicationContext(@Nullable ApplicationContext parent) {
        super(parent);
    }


    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
        beanDefinitionReader.setResourceLoader(this);
        loadBeanDefinitions(beanDefinitionReader);
    }

    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
        Resource[] configResources = getConfigResources();
        if (configResources != null) {
            for (Resource r : configResources) {
                reader.loadBeanDefinitions(r);
            }
        }
        String[] configLocations = getConfigLocations();
        if (configLocations != null) {
            for (String location : configLocations) {
                reader.loadBeanDefinitions(location);
            }
        }
    }


    @Nullable
    protected Resource[] getConfigResources() {
        return null;
    }
}
